package org.dru.clay.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;

public class URIUtil {
	private static final Pattern X_SLASH = Pattern.compile("//+");

	public static URI rebase(URI uri, URI from, URI to) {
		try {
			final String path = uri.getPath();
			final String base = from.getPath();
			final String rebase = path.substring(base.length());
			return new URI(simplify(to.toString() + "/" + rebase));
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	private static String simplify(String string) {
		return X_SLASH.matcher(string).replaceAll("/");
	}
}
